<template>
  <div>
    <el-upload
      action=""
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :before-upload="beforeAvatarUpload"
      :default-file-list="fileList"
      v-bind="$attrs"
      :file-list="fileList"
      :http-request="upload"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
  </div>
</template>
<script>
// 安装"v-viewer": "^1.6.4"查看图片,
// import Viewer from 'v-viewer'
// import 'viewerjs/dist/viewer.css'
// Vue.use(Viewer) 在main引入
import { upload } from "@/api/common";
export default {
  props: {
    defaultValue: {
      type: Array,
      default: [],
    },
  },
  data() {
    return {
      url: "",
      fileList: [],
    };
  },
  created() {},
  watch: {
    fileList: {
      deep: true,
      immediate: true,
      handler(val) {
        this.$emit("change", val);
        this.$emit("input", val);
      },
    },
    defaultValue: {
      deep: true,
      immediate: true,
      handler(val) {
        this.fileList = val;
      },
    },
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/gif" ||
        file.type === "image/jpg" ||
        file.type === "image/jpeg" ||
        file.type === "image/png";
      const isLt20M = file.size / 1024 / 1024 < 20; // 将1改为20，表示20MB
      if (!isJPG) {
        this.$message.error("仅支持gif,jpg,png格式的图片！");
      }
      if (!isLt20M) {
        this.$message.error("上传图片大小不能超过 20MB!"); // 修改错误消息为20MB
      }
      return isJPG && isLt20M;
    },
    handleRemove(file, fileList) {
      // const index = this.fileList.indexOf(file);
      // const newFileList = this.fileList.slice();
      // newFileList.splice(index, 1);
      // this.fileList = newFileList;
      // remFile(file.uid).then((res) => {
      //   if (res.data) {
      //     this.$message.success('删除成功')
      //   }
      // })
      return new Promise((resolve, reject) => {
        // this.$confirm(`确定移除 ${file.name}？`)
        //   .then(() => {
        //     // 用户点击了确定，文件将被移除
        //     resolve(true);
        //     // 执行其他操作...
        //     // eslint-disable-next-line vue/no-mutating-props
        //     this.defaultValue = fileList;
        //   })
        //   .catch(() => {
        //     // 用户点击了取消，文件将保留
        //     resolve(false);
        //   });
        const newFileList = Object.assign([], this.fileList);
        newFileList.forEach((item, index) => {
          if (item.uid === file.uid) {
            newFileList.splice(index, 1);
          }
        });
        this.fileList = newFileList;
      });
    },
    upload(param) {
      const formData = new FormData();
      formData.append("file", param.file);
      upload(formData).then((res) => {
        if (res.code == 200) {
          this.$message.success("成功");
          this.fileList = [
            ...this.fileList,
            {
              name: res.data.originalFileName,
              size: res.data.size,
              type: res.data.fileType,
              uid: res.data.id,
              status: "done",
              url: `${process.env.VUE_APP_BASE_API}/file/getFile/${res.data.bucketName}/${res.data.name}`,
              fileName: res.data.originalFileName,
            },
          ];
        } else {
          this.$message.error("失败");
        }
      });
    },
    handlePictureCardPreview(file) {
      const fileListUrl = this.fileList.map((item) => item.url);
      const fileListName = this.fileList.map((item) => item.name);
      const index = fileListUrl.indexOf(file.url);
      this.$viewerApi({
        images: fileListUrl,
        options: {
          initialViewIndex: index,
          title: [
            1,
            (image, imageData) =>
              `${returnName(image.alt)} (${imageData.naturalWidth} × ${
                imageData.naturalHeight
              })`,
          ],
        },
      });
      function returnName(val) {
        return fileListName[
          fileListUrl.findIndex((item) => item.includes(val))
        ];
      }
    },
  },
};
</script>

<style scoped lang="scss">
.custom-image-preview {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.custom-image-preview img {
  max-width: 80%;
  max-height: 80%;
  border: 2px solid #fff;
  cursor: pointer;
}
</style>